package com.l024.meet;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.gson.Gson;
import com.l024.framework.base.BaseUIActivity;
import com.l024.framework.bmob.BmobManager;
import com.l024.framework.entity.Constants;
import com.l024.framework.gson.TokenBean;
import com.l024.framework.manager.DialogManager;
import com.l024.framework.manager.HttpManger;
import com.l024.framework.manager.PermissionManager;
import com.l024.framework.utils.Logutils;
import com.l024.framework.utils.SpUtils;
import com.l024.framework.view.DialogView;
import com.l024.meet.fragment.ChatFragment;
import com.l024.meet.fragment.MeFragment;
import com.l024.meet.fragment.SquareFragment;
import com.l024.meet.fragment.StartFragment;
import com.l024.meet.service.CloudService;
import com.l024.meet.ui.FirstUploadActivity;
import com.yanzhenjie.permission.runtime.Permission;

import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class MainActivity extends BaseUIActivity implements View.OnClickListener {
    //切换
    private FrameLayout mMainLayout;
    //星球
    private LinearLayout llStar;
    private ImageView ivStar;
    private TextView tvStar;
    private StartFragment startFragment = null;
    private FragmentTransaction mStartTransaction;

    //广场
    private LinearLayout llSquare;
    private ImageView ivSquare;
    private TextView tvSquare;
    private SquareFragment squareFragment = null;
    private FragmentTransaction mSquareTransaction;

    //聊天
    private LinearLayout llChat;
    private ImageView ivChat;
    private TextView tvChat;
    private ChatFragment chatFragment = null;
    private FragmentTransaction mChatTransaction;
    //我的
    private LinearLayout llMe;
    private ImageView ivMe;
    private TextView tvMe;
    private MeFragment meFragment = null;
    private FragmentTransaction mMeTransaction;

    //权限
    private String[] permissions = {Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_PHONE_STATE,Permission.CAMERA};
    //跳转到FirstUploadActivity页面返回码
    private static final int FIRST_UPLOAD_RESULT = 1000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        checkPermission();
        mMainLayout = (FrameLayout) findViewById(R.id.mMainLayout);
        llStar = (LinearLayout) findViewById(R.id.ll_star);
        ivStar = (ImageView) findViewById(R.id.iv_star);
        tvStar = (TextView) findViewById(R.id.tv_star);
        llSquare = (LinearLayout) findViewById(R.id.ll_square);
        ivSquare = (ImageView) findViewById(R.id.iv_square);
        tvSquare = (TextView) findViewById(R.id.tv_square);
        llChat = (LinearLayout) findViewById(R.id.ll_chat);
        ivChat = (ImageView) findViewById(R.id.iv_chat);
        tvChat = (TextView) findViewById(R.id.tv_chat);
        llMe = (LinearLayout) findViewById(R.id.ll_me);
        ivMe = (ImageView) findViewById(R.id.iv_me);
        tvMe = (TextView) findViewById(R.id.tv_me);
        //设置监听
        llStar.setOnClickListener(this);
        llSquare.setOnClickListener(this);
        llChat.setOnClickListener(this);
        llMe.setOnClickListener(this);

        //设置文本
        tvStar.setText(getString(R.string.text_main_star));
        tvSquare.setText(getString(R.string.text_main_square));
        tvChat.setText(getString(R.string.text_main_chat));
        tvMe.setText(getString(R.string.text_main_me));

        //初始化Fragment
        initFragment();

        //切换默认选项卡
        checkMainTab(0);
        //检查Token
        checkToken();
        //模拟用户数据
        //SimulationData.testData();
    }

    /**
     * 检查Tokne 用来判断是不是新用户。引导去填写资料
     */
    private void checkToken(){
        //获取Token的三个参数 1.用户Id 2.头像地址 3.昵称
        String token = SpUtils.getInstance().getString(Constants.SP_TOKEN,"");
        if(!TextUtils.isEmpty(token)){
            //启动云服务去连接云服务
            startService(new Intent(this,CloudService.class));
        }else{
            //有三个参数
            String tokenPhoto = BmobManager.getInstance().getUser().getTokenPhoto();
            String tokenNickName = BmobManager.getInstance().getUser().getTokenNickName();
            if(!TextUtils.isEmpty(tokenPhoto)&&!TextUtils.isEmpty(tokenNickName)){
                //创建Token
                createToken();
            }else{
                //创建上传对话框
                createUploadDialog();
            }
        }
    }

    /**
     * 创建Token
     */
    private void createToken(){
        //创建token
        /**
         * 1.去融云获取
         * 2.
         */
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("userId",BmobManager.getInstance().getUser().getObjectId());
        hashMap.put("name",BmobManager.getInstance().getUser().getNickName());
        hashMap.put("portraitUri",BmobManager.getInstance().getUser().getPhoto());
        //通过okHttp请求Token
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                //执行请求
                String json = HttpManger.getInstance().postCloudToken(hashMap);
                emitter.onNext(json);
                emitter.onComplete();
            }
            //线程调度
        }).subscribeOn(Schedulers.newThread())
        .subscribeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Logutils.i("获取token:"+s);
                parsingCloudToken(s);
            }
        });
    }

    /**
     * 启动融云服务
     */
    private void startCloudService(){
        Logutils.i("startCloudService");
        startService(new Intent(this, CloudService.class));
        //检查更新
    }

    /**
     * 解析json
     */
    private void parsingCloudToken(String s){
        TokenBean tokenBean = new Gson().fromJson(s,TokenBean.class);
        if(tokenBean!=null){
           if(tokenBean.getCode()==200){
               if(!TextUtils.isEmpty(tokenBean.getToken())){
                   //保存Token
                   SpUtils.getInstance().putString(Constants.SP_TOKEN,tokenBean.getToken());
                   startCloudService();
               }
           } else if (tokenBean.getCode() == 2007) {
               Toast.makeText(this, "注册人数已达上限，请替换成自己的Key", Toast.LENGTH_SHORT).show();
           }
        }
    }

    /**
     * 创建上传对话框
     */
    private void createUploadDialog(){
        DialogView uploadView = DialogManager.getInstance().initView(this, R.layout.dialog_first_upload);
        DialogManager.getInstance().setCancelable(uploadView);
        ImageView ivUpload = uploadView.findViewById(R.id.iv_go_upload);
        ivUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(uploadView);
                Intent intent = new Intent(MainActivity.this, FirstUploadActivity.class);
                startActivityForResult(intent,FIRST_UPLOAD_RESULT);
            }
        });
        DialogManager.getInstance().show(uploadView);
    }


    /**
     * 初始化Fragment
     */
    private void initFragment(){
        //星球
        if(startFragment==null){
            startFragment = new StartFragment();
            mStartTransaction = getSupportFragmentManager().beginTransaction();
            mStartTransaction.add(R.id.mMainLayout,startFragment);
            mStartTransaction.commit();
        }
        //广场
        if(squareFragment==null){
            squareFragment = new SquareFragment();
            mSquareTransaction = getSupportFragmentManager().beginTransaction();
            mSquareTransaction.add(R.id.mMainLayout,squareFragment);
            mSquareTransaction.commit();
        }
        //聊天
        if(chatFragment==null){
            chatFragment = new ChatFragment();
            mChatTransaction = getSupportFragmentManager().beginTransaction();
            mChatTransaction.add(R.id.mMainLayout,chatFragment);
            mChatTransaction.commit();
        }
        //我的
        if(meFragment==null){
            meFragment = new MeFragment();
            mMeTransaction = getSupportFragmentManager().beginTransaction();
            mMeTransaction.add(R.id.mMainLayout,meFragment);
            mMeTransaction.commit();
        }
    }

    /**
     * 显示Fragment
     */
    private void showFragment(Fragment fragment){
        if(fragment!=null){
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            //每次显示之前先隐藏所有
            hideAll(fragmentTransaction);
            fragmentTransaction.show(fragment);
            //提交
            fragmentTransaction.commitAllowingStateLoss();
        }
    }

    /**
     * 隐藏Fragment
     */
    private void hideAll(FragmentTransaction transaction){
        if(mStartTransaction!=null){
            transaction.hide(startFragment);
        }
        if(mSquareTransaction!=null){
            transaction.hide(squareFragment);
        }
        if(mChatTransaction!=null){
            transaction.hide(chatFragment);
        }
        if(mMeTransaction!=null){
            transaction.hide(meFragment);
        }
    }

    /**
     * 切换直接选项卡
     * 0：星球
     * 1：广场
     * 2：聊天
     * 3：我的
     */
    private void checkMainTab(int index){
        switch (index){
            case 0:{
                showFragment(startFragment);
                //修改选中图片
                ivStar.setImageResource(R.drawable.img_star_p);
                ivSquare.setImageResource(R.drawable.img_square);
                ivChat.setImageResource(R.drawable.img_chat);
                ivMe.setImageResource(R.drawable.img_me);

                //修改文字颜色
                tvStar.setTextColor(getResources().getColor(R.color.colorAccent));
                tvSquare.setTextColor(Color.BLACK);
                tvChat.setTextColor(Color.BLACK);
                tvMe.setTextColor(Color.BLACK);
                break;
            }
            case 1:{
                showFragment(squareFragment);
                //修改选中图片
                ivStar.setImageResource(R.drawable.img_star);
                ivSquare.setImageResource(R.drawable.img_square_p);
                ivChat.setImageResource(R.drawable.img_chat);
                ivMe.setImageResource(R.drawable.img_me);

                //修改文字颜色
                tvStar.setTextColor(Color.BLACK);
                tvSquare.setTextColor(getResources().getColor(R.color.colorAccent));
                tvChat.setTextColor(Color.BLACK);
                tvMe.setTextColor(Color.BLACK);
                break;
            }
            case 2:{
                showFragment(chatFragment);
                //修改选中图片
                ivStar.setImageResource(R.drawable.img_star);
                ivSquare.setImageResource(R.drawable.img_square);
                ivChat.setImageResource(R.drawable.img_chat_p);
                ivMe.setImageResource(R.drawable.img_me);

                //修改文字颜色
                tvStar.setTextColor(Color.BLACK);
                tvSquare.setTextColor(Color.BLACK);
                tvChat.setTextColor(getResources().getColor(R.color.colorAccent));
                tvMe.setTextColor(Color.BLACK);
                break;
            }
            case 3:{
                showFragment(meFragment);
                //修改选中图片
                ivStar.setImageResource(R.drawable.img_star);
                ivSquare.setImageResource(R.drawable.img_square);
                ivChat.setImageResource(R.drawable.img_chat);
                ivMe.setImageResource(R.drawable.img_me_p);

                //修改文字颜色
                tvStar.setTextColor(Color.BLACK);
                tvSquare.setTextColor(Color.BLACK);
                tvChat.setTextColor(Color.BLACK);
                tvMe.setTextColor(getResources().getColor(R.color.colorAccent));
                break;
            }
        }
    }

    /**
     * 申请权限
     */
    private void checkPermission(){
        PermissionManager.requestPermission(this, new PermissionManager.PermissionQuestListener() {
            @Override
            public void onGranted() {
                Logutils.i("权限申请成功");
            }

            @Override
            public void onDenied(List<String> data) {
                Logutils.e("权限申请失败");
            }
        },permissions);
    }

    /**
     * 防止重叠
     * 当应用内存紧张的时候。系统会回收到Fragment对象
     * 再一次进入会重新创建Fragment
     * 非原来对象，我们无法控制会导致重叠
     * @param fragment
     */

    @Override
    public void onAttachFragment(@NonNull Fragment fragment) {
        if(startFragment!=null&&fragment instanceof  StartFragment){
            startFragment = (StartFragment) fragment;
        }
        if(squareFragment!=null&&fragment instanceof  SquareFragment){
            squareFragment = (SquareFragment) fragment;
        }
        if(chatFragment!=null&&fragment instanceof  ChatFragment){
            chatFragment = (ChatFragment) fragment;
        }
        if(meFragment!=null&&fragment instanceof  MeFragment){
            meFragment = (MeFragment) fragment;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_star:{
                checkMainTab(0);
                break;
            }
            case R.id.ll_square:{
                checkMainTab(1);
                break;
            }
            case R.id.ll_chat:{
                checkMainTab(2);
                break;
            }
            case R.id.ll_me:{
                checkMainTab(3);
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == FIRST_UPLOAD_RESULT){
                //上传头像成功
                checkToken();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
